//
//  EmotionViewController.swift
//  表情键盘
//
//  Created by zhangguo on 15/10/17.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
//可重用标示符
let GFcollectiongViewIdentifier = "GFcollectiongViewIdentifier"

//表情键盘输入控制器
class EmotionViewController: UIViewController {
    
    //定义一个表情闭包
    //选择表情的回调
    var selecterEmoticonCallBack:(emotion: Emoticon) ->()
    
    //构造函数
    init(SelectorEmoticon: (emotion: Emoticon) ->()) {
        
        selecterEmoticonCallBack = SelectorEmoticon
        
        super.init(nibName:nil,bundle:nil)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //监听方法,此处不加privite,否则外界访问不到这个方法
     func clickItem(item: UIBarButtonItem) {
        
        let  index = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        
        print(item.tag)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.yellowColor()
        setupUI()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
       
    }

    //设置控件
    func setupUI() {
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        
        
          //设置约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        let viewDict = ["cv":collectionView,"tb":toolbar]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        //准备控件
        prepareToolbar()
        preparCollectionView()
    }
    //设置cv的
    private func preparCollectionView () {
        collectionView.registerClass(EmotionCell.self, forCellWithReuseIdentifier: GFcollectiongViewIdentifier)
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.whiteColor()
        
        collectionView.delegate = self
        
    }
    
    //准备工具栏
    private func prepareToolbar() {
        toolbar.tintColor = UIColor.darkGrayColor()
        
        var indxs = 0
        var items = [UIBarButtonItem]()
        
        for p in packages {
            items.append(UIBarButtonItem(title: p.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            
            items.last?.tag = indxs++
            
            //加一个弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        //加入弹簧后移除最后一个空的位置
        items.removeLast()
        toolbar.items = items
    }
    
    //懒加载控件
    //表情包数据
    private lazy var packages = EmoticonsPackage.packages()
    
    private lazy var toolbar = UIToolbar()
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: GFEmoticonLayout())
    
    //表情键盘布局  - 私有类 在这里设置布局
    private class GFEmoticonLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
           //设置布局属性
            let w = collectionView!.bounds.width / 7.0
            let y = (collectionView!.bounds.height - 3 * w) * 0.5
            itemSize = CGSize(width: w, height: w)
            
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            //可以让collectionview整体居中，距离上下距离一致
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }

}
//数据源方法


extension EmotionViewController: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //获取当前的表情
       let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        
        selecterEmoticonCallBack(emotion: emoticon)
    }
    
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        //返回分组的数量，表情包数量
        return packages.count
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     return packages[section].emoticons?.count ?? 0
        
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GFcollectiongViewIdentifier, forIndexPath: indexPath) as!EmotionCell
        
        cell.emoticon = packages[indexPath.section].emoticons![indexPath.item]
        return cell
        
    }
}

//表情cell
private class EmotionCell: UICollectionViewCell {
    
    var emoticon: Emoticon? {
        didSet {
            //设置按钮显示的图像
            emoticonButtor.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
           //设置emoji
            emoticonButtor.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            //禁止button交互、让代理接管
            emoticonButtor.userInteractionEnabled = false
            
            //判断是否是删除按钮
            if emoticon!.removeEmoticon {
                emoticonButtor.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)

                emoticonButtor.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
            
        }
    }
    
    //此时frame已经有准确的值了
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        emoticonButtor.backgroundColor = UIColor.whiteColor()
        
        //设置字体大小，emoji的大小就是字体大小
        emoticonButtor.titleLabel?.font = UIFont.systemFontOfSize(32)
        //设定cgrectInset的x，y向内缩进4
        emoticonButtor.frame = CGRectInset(bounds, 4, 4)
        addSubview(emoticonButtor)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载控件
    private lazy var emoticonButtor = UIButton()
}

